package com.software.modelcenter.service;

import com.aspose.threed.Scene;
import com.software.modelcenter.entity.ModelMine;
import com.software.modelcenter.repository.ModelMineRepository;
import com.software.modelcenter.utils.FormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@Service
@Transactional
public class ModelMineService {

    @Autowired
    private ModelMineRepository modelMineRepository;

    public List<ModelMine> ListModelMineById(String userId){
        return modelMineRepository.ListModelMineById(userId);
    }

    public void saveModelMine(String userId, String file, MultipartFile image) {
        String imageName = saveImage(image);
        file = FormatUtil.hexStringToString(file);

        Path rootLocation = Paths.get("model");
        if(Files.notExists(rootLocation)){
            try {
                Files.createDirectories(rootLocation);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Path path = rootLocation.resolve("123.fbx");
        byte[] strToBytes = file.getBytes();
        try {
            Files.write(path, strToBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("成功保存文件");


        String id = String.valueOf(UUID.randomUUID());
        FormatUtil.exportFbx2Obj(String.valueOf(id));
        FormatUtil.formatOBJ(String.valueOf(id));
        ModelMine modelMine = new ModelMine();
        modelMine.setUserId(userId);
        modelMine.setModelName("自制模型");
        modelMine.setModelId(id);
        modelMine.setModelNote(imageName);
        modelMine.setUserType(id);
        modelMine.setLastTime(new Timestamp(System.currentTimeMillis()));

        modelMineRepository.save(modelMine);


    }

    private String saveImage(MultipartFile image) {
        String fileName = UUID.randomUUID().toString() + ".png";

        try (FileOutputStream fos = new FileOutputStream(new File("model_img/" + fileName))) {
            fos.write(image.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }

    public ModelMine updateModelMine(ModelMine modelMine) {
        return modelMineRepository.save(modelMine);
    }

    public void deleteModelMineByModelId(String modelId) {
        modelMineRepository.deleteByModelId(modelId);
    }


}